/*
   Copyright 2007 Jeremy Wales

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

package com.googlecode.cpbi;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.jar.JarEntry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

import com.googlecode.cpbi.util.ClassLoaderUtils;
import com.googlecode.cpbi.util.FileUtils;
import com.googlecode.cpbi.util.Jar;
import com.googlecode.cpbi.util.Osgi;
import com.googlecode.cpbi.util.PackageUtils;

/**
 * @author Jeremy Wales
 */
public final class ClassPathBundleInstaller implements Runnable {
	public static final Log LOG = LogFactory.getLog(ClassPathBundleInstaller.class);
	private static final String ALL_FILES = "**";

	private final Map exportedAndUsedPackages = new TreeMap();
	private final Osgi osgi;
	private final String[] excludedPackagePatterns;

	public ClassPathBundleInstaller(Osgi osgiImplementation) {
		osgi = osgiImplementation;
		excludedPackagePatterns = osgi.getBootDelegationPackagePatterns();
	}

	public void run() {
		URLClassLoader systemClassLoader = ClassLoaderUtils.getSystemClassLoader();
		URL[] classPathUrls = systemClassLoader.getURLs();
		for (int i = 0; i < classPathUrls.length; i++) {
			process(classPathUrls[i]);
		}
		new ExportBundleInstaller(osgi).installSystemBundleFragmentExporting(exportedAndUsedPackages);
	}

	private void process(URL location) {
		try {
			if (FileUtils.isDirectory(location)) {
				addToExportsThePackagesUnder(location);
			} else {
				processPotentialJarAt(location);
			}
		} catch (IOException e) {
			LOG.error("Could not access Class Path entry '" + location + "'.", e);
		}
	}

	private void addToExportsThePackagesUnder(URL directory) throws IOException {
		Resource[] resources = FileUtils.getResourcesMatching(directory + ALL_FILES);
		for (int i = 0; i < resources.length; i++) {
			Resource resource = resources[i];
			if (!resource.getFile().isDirectory()) {
				addToExportsThePackageOf(resource, directory);
			}
		}
	}

	private void addToExportsThePackageOf(Resource resource, URL rootLocation) throws IOException {
		String relativeName = FileUtils.getRelativePathOf(resource.getURL(), rootLocation);
		String exportedPackage = PackageUtils.getPackageNameOf(relativeName);
		if (!PackageUtils.matches(exportedPackage, excludedPackagePatterns)) {
			Set usedPackages = createOrAccessUsedPackagesOf(exportedPackage);
			if (relativeName.endsWith(".class")) {
				String[] excluded = StringUtils.addStringToArray(excludedPackagePatterns, exportedPackage);
				usedPackages.addAll(PackageUtils.getPackageDependenciesOf(resource, excluded));
			}
		}
	}

	private Set createOrAccessUsedPackagesOf(String exportPackage) {
		Set usedPackages = (Set) exportedAndUsedPackages.get(exportPackage);
		if (usedPackages == null) {
			exportedAndUsedPackages.put(exportPackage, usedPackages = new TreeSet());
		}
		return usedPackages;
	}

	private void processPotentialJarAt(URL location) throws IOException {
		Jar jar = null;
		try {
			jar = new Jar(location);
			if (jar.exists()) {
				if (jar.isOsgiBundle()) {
					osgi.tryToInstallBundleFrom(location.toString());
				} else {
					addToExportsThePackagesIn(jar);
				}
			}
		} finally {
			jar.close();
		}
	}

	private void addToExportsThePackagesIn(Jar jar) throws IOException {
		JarEntry jarEntry = null;
		while ((jarEntry = jar.getNextEntry()) != null) {
			if (!jarEntry.isDirectory()) {
				addToExportsThePackageOf(jar.getEntryNamed(jarEntry.getName()), jar.getLocation());
			}
		}
	}
}
